﻿using System;
using log4net;
using System.Linq;
using System.Collections.Generic;
using Century.Model;
using System.Threading;
using Century.EnterpriseLibrary.Caching;
using Century.EnterpriseLibrary.Configuration;

namespace Century.EnterpriseLibrary.Globalization
{
    /// <summary>
    /// Class to handle localization
    /// </summary>
    public static class GlobalizationManager
    {
        //internal static string CurrentSite
        //{
        //    get
        //    {
        //        return Thread.CurrentThread.CurrentUICulture.Name;
        //    }
        //}
        private static object translationSemafor = new object();
        public static ILog Log
        {
            get
            {
                return Century.EnterpriseLibrary.LogHandler.Loging.LogWithName("GlobalizationManager");
            }
        }

        #region [ Public Method(s) ]

        /// <summary>
        /// Method to translate a key.
        /// </summary>
        /// <param name="translationKey">Key of translation</param>
        /// <returns>Translated Value</returns>
        public static string CMSTranslate(string category, string translationKey, string defaultValue, int siteId)
        {
            string ctgry = string.IsNullOrEmpty(category) ? string.Empty : "." + category;

            string areaPerfix = "CMS";
            if (translationKey.StartsWith("GLB.") ||
                translationKey.StartsWith("LAP.") ||
                translationKey.StartsWith("SCA.") ||
                translationKey.StartsWith("REG.") ||
                translationKey.StartsWith("CMS."))
            {
                areaPerfix = translationKey.Substring(0, 3);
                translationKey = translationKey.Substring(4);
            }

            return Translate(string.Format("{0}{1}.{2}", areaPerfix, ctgry, translationKey), defaultValue, siteId);

        }

        public static bool CMSUpdateTranslation(string category, string translationKey, string newValue, int siteId)
        {
            string ctgry = string.IsNullOrEmpty(category) ? string.Empty : "." + category;

            string areaPerfix = "CMS";
            if (translationKey.StartsWith("GLB.") ||
                translationKey.StartsWith("LAP.") ||
                translationKey.StartsWith("SCA.") ||
                translationKey.StartsWith("REG.") ||
                translationKey.StartsWith("CMS."))
            {
                areaPerfix = translationKey.Substring(0, 3);
                translationKey = translationKey.Substring(4);
            }

            return UpdateLabelValue(string.Format("{0}{1}.{2}", areaPerfix, ctgry, translationKey), newValue, siteId);
        }



        /// <summary>
        /// Method to translate a key.
        /// </summary>
        /// <param name="translationKey">Key of translation</param>
        /// <returns>Translated Value</returns>
        public static string Translate(string translationKey, int siteId)
        {
            return Translate(translationKey, translationKey, siteId);
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="translationKey"></param>
        /// <param name="defaultValue"></param>
        /// <returns></returns>
        internal static TranslationText GetLableTranslation(string translationKey, string defaultValue, int siteId)
        {
            TranslationText translationText;
            lock (translationSemafor)
            {
                using (CenturyDbContext db = new CenturyDbContext())
                {
                    if (!db.TranslationTexts.Any(c => c.TranslationKey.ToLower() == translationKey.ToLower() && c.SiteId == siteId))
                    {
                        translationText = new TranslationText { TranslationKey = translationKey, TranslationValue = defaultValue, SiteId = siteId };

                        db.TranslationTexts.Add(translationText);
                        db.SaveChanges();
                    }
                    else
                    {
                        translationText = db.TranslationTexts.FirstOrDefault(c => c.TranslationKey.ToLower() == translationKey.ToLower() && c.SiteId == siteId);
                    }
                }
            }
            return translationText;
        }
        /// <summary>
        ///  Method to translate a key. 
        /// </summary>
        /// <param name="translationKey">Key of translation</param>
        /// <param name="defaultValue">Default Value</param>
        /// <returns>Translated Value</returns>
        public static string Translate(string translationKey, string defaultValue, int siteId)
        {
            try
            {
                TranslationText translationText = CacheService.Get<TranslationText>(string.Format("lbl_{0}_{1}", translationKey.ToLower(), siteId), () => GetLableTranslation(translationKey, defaultValue, siteId), ConfManager.Instance.CacheManager.CacheExTime);
                return translationText.TranslationValue;
            }
            catch (Exception exc)
            {
                Log.Error("Error on translation text", exc);
                return string.Empty;
            }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="translationKey"></param>
        /// <param name="newValue"></param>
        /// <returns></returns>
        public static bool UpdateLabelValue(string translationKey, string newValue, int siteId)
        {
            try
            {
                lock (translationSemafor)
                {
                    using (CenturyDbContext db = new CenturyDbContext())
                    {
                        TranslationText tt = db.TranslationTexts.FirstOrDefault(c => c.TranslationKey.ToLower() == translationKey.ToLower() && c.SiteId == siteId);
                        if (tt == null)
                        {
                            tt = new TranslationText { TranslationKey = translationKey, TranslationValue = newValue, SiteId = siteId };
                            db.TranslationTexts.Add(tt);
                            db.SaveChanges();
                        }

                        else
                        {
                            tt.TranslationValue = newValue;
                            db.SaveChanges();

                        }

                        CacheService.Add(string.Format("lbl_{0}_{1}", translationKey.ToLower(), siteId), tt, ConfManager.Instance.CacheManager.CacheExTime);
                    }
                }
                return true;
            }
            catch (Exception exc)
            {
                Log.Error("Error on update translation text", exc);
                return false;

            }

        }
        public static List<TranslationText> GetAll(int siteId)
        {
            using (CenturyDbContext db = new CenturyDbContext())
            {
                return db.TranslationTexts.Where(c => c.SiteId == siteId).ToList();
            }
        }
        #endregion


    }
}
